package com.edgar.paysdk.ali

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.alipay.sdk.app.PayTask
import com.edgar.paysdk.PayException
import com.edgar.paysdk.PayPlatform
import com.edgar.paysdk.PayReq
import com.edgar.paysdk.PayType
import com.edgar.paysdk.ali.PayResult.ErrorCode.CANCEL
import com.edgar.paysdk.ali.PayResult.ErrorCode.NET_ERROR
import com.edgar.paysdk.ali.PayResult.ErrorCode.HANDLE
import com.edgar.paysdk.ali.PayResult.ErrorCode.SUCCESS
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * Created by edgar on 18-1-21.
 */
class AliPay(context: Context) : PayPlatform(context) {

    companion object{
        @JvmStatic val TAG = "AliPay"
    }

    private val mHandle:Handler = Handler(Looper.getMainLooper())
    private val mExecutorService:ExecutorService = Executors.newSingleThreadExecutor()
    override fun getPayType(): PayType = PayType.Ali

    override fun doPay(payReq: PayReq): Boolean {
        val activity = payReq.getActivity()
        mExecutorService.execute {
            val aliPayTask = PayTask(activity)
            val payInfo = payReq.getOrderInfo() + "&sign=" + payReq.getSign()
            val result = aliPayTask.payV2(payInfo,true)
            val payResult = PayResult.to(result)
            val status = payResult.resultStatus
            when(status){
                CANCEL->{
                    Log.d(TAG,"AliPay user cancel")
                    mHandle.post {
                        mPayListener?.onCancel(this)
                    }
                }
                NET_ERROR->{
                    val errMsg = "pay network error"
                    Log.d(TAG,errMsg)
                    mHandle.post {
                        mPayListener?.onError(this,PayException(errMsg))
                    }
                }
                SUCCESS->{
                    Log.d(TAG,"Ali pay success")
                    mHandle.post {
                        mPayListener?.onSuccess(this)
                    }
                }
                HANDLE ->{
                    Log.d(TAG,"Ali pay handle")
                    mHandle.post {
                        mPayListener?.onPayHandle(this)
                    }
                }
                else->{
                    val errMsg = "Ali pay failed"
                    Log.d(TAG,errMsg)
                    mHandle.post {
                        mPayListener?.onError(this,PayException(errMsg))
                    }
                }
            }
        }
        return true
    }
}